package com.hundsun.cprs.yyt.service.rabbit.listener;

import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.account.domain.AccountStat;
import com.hundsun.cprs.yyt.service.account.service.AccountDailyLimitCacheService;
import com.hundsun.cprs.yyt.service.account.service.AccountStatService;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.enums.EnumSmsCode;
import com.hundsun.cprs.yyt.service.common.service.RemoteBrokerService;
import com.hundsun.cprs.yyt.service.common.service.RemoteSmsService;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.order.domain.OrderItem;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.trade.domain.TradeMatchDetail;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustFrom;

import com.hundsun.cprs.yyt.util.MoneyUtils;
import com.hundsun.cprs.yyt.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EntrustPostProcessListener implements MessageListener {

    protected Log logger = LogFactory.getLog(EntrustPostProcessListener.class);

    @Autowired
    private AccountStatService accountStatService;
    @Autowired
    private RemoteBrokerService remoteBrokerService;
    @Autowired
    private AccountDailyLimitCacheService accountDailyLimitCacheService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private RemoteSmsService remoteSmsService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Value("${goldenFlower_user_number_segment}")
    private String goldenFlowerNumberSegment;

    @Override
    public void onMessage(Message message) {
        String receviedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        TradeEntrust tradeEntrust = JSON.parseObject(new String(message.getBody()), TradeEntrust.class);
        if (receviedRoutingKey.equals(RoutingKeyConstants.YYT_ENTRUST_STATUS_DEALT) 
            || receviedRoutingKey.equals(RoutingKeyConstants.YYT_ENTRUST_STATUS_PART_CANCELED)){
            //已成或者部撤状态处理分佣,库存变更和短信提醒
            handleCommissionAndAccountStat(tradeEntrust);
        }else if (receviedRoutingKey.equals(RoutingKeyConstants.YYT_TRADE_ENTRUST_COMMIT_SUCCESS)){
            //已上报状态处理用户每日挂售金额上限和挂售数量上限
            //handleDailySellAmountAndSellMoneyToaCache(tradeEntrust);
        }else if (receviedRoutingKey.equals(RoutingKeyConstants.YYT_ENTRUST_STATUS_PART_DEALT)){
            //监听部成消息，发送短信提醒
            TradeMatchDetail detail = JSON.parseObject(new String(message.getBody()), TradeMatchDetail.class);
            sendSmsToReciver(null,detail,EnumSmsCode.PART_CLINCH_SMS_CODE.getCode());
        }
    }

    //处理分佣和交易账户统计
    protected void handleCommissionAndAccountStat(TradeEntrust tradeEntrust){
        try{
            //处理分佣
            tradeCommission(tradeEntrust);
        }catch (Exception e){
            logger.error("分佣处理失败：委托单id:"+tradeEntrust.getId()+",错误信息：",e);
        }
        try{
            //处理交易账户统计
            tradeAccountStatEarn(tradeEntrust);
        }catch (Exception e){
            logger.error("交易账户统计失败：委托单id:"+tradeEntrust.getId()+",错误信息：",e);
        }
        try{
            //库存变更
            handleStock(tradeEntrust);
        }catch (Exception e){
            logger.error("库存变更失败：委托单id:"+tradeEntrust.getId()+",错误信息：",e);
        }
        try{
            //发送匹配成功短信
            sendSmsToReciver(tradeEntrust,null,EnumSmsCode.CLINCH_SMS_CODE.getCode());
        }catch (Exception e){
            logger.error("短信发送失败：委托单id:"+tradeEntrust.getId()+",错误信息：",e);
        }
    }
    
    protected void tradeCommission(TradeEntrust tradeEntrust){
        //只有委买方向才进行返佣
        if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.BUY.getCode().toString())){
            //金莱花号段的会员不在本平台返佣
            if (validateIsGoldenFlower(tradeEntrust)){
                return;
            }
            remoteBrokerService.tradeSplitCommission(tradeEntrust.getId());
        }
    }

    protected void tradeAccountStatEarn(TradeEntrust tradeEntrust){
        //更新账户的累计赚得金额
        //只有委卖方向才进行委售成功累计赚得金额
        if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.SELL.getCode().toString())){
            AccountStat accountStat = new AccountStat();
            accountStat.setUserId(tradeEntrust.getUserId());
            accountStat.setEarnedSum(tradeEntrust.getGainBusinessFund());
            accountStatService.updateAccountStat(accountStat);
        }
    }

    /*protected void tradeAccountStatTime(TradeEntrust tradeEntrust){
        //更新账户的委售次数，上报成功就算
        //只有委卖方向才进行委售成功次数的统计
        if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.SELL.getCode().toString())){
            AccountStat accountStat = new AccountStat();
            accountStat.setUserId(tradeEntrust.getUserId());
            accountStat.setTrusteTime(1L);
            accountStatService.updateAccountStat(accountStat);
        }
    }*/

    //处理用户每日挂售金额上限,挂售次数上限
    protected void handleDailySellAmountAndSellMoneyToaCache(TradeEntrust tradeEntrust){
        //只有委卖才进行此账户统计
        if (tradeEntrust.getEntrustBs().equals(EnumEntustBSType.SELL.getCode().toString())){
            accountDailyLimitCacheService.addUserSellAmountToCache(tradeEntrust);
            accountDailyLimitCacheService.addUserSellMoneyToCache(tradeEntrust);
        }
    }

    protected void handleStock(TradeEntrust tradeEntrust){

        // 更新商品的预占库存和实际库存
        if (EnumEntustFrom.FROM_PLATFORM.getCode() == tradeEntrust.getEntrustFrom()) {
            // 平台挂单无订单，不需处理
            return;
        }
        if (tradeEntrust.isSell()) {
            // 批发区商品库存，优先先扣除已成的数量，获取订单信息
            OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
            if (orderInfo != null) {
                // 若已委售全部成功，则更新订单状态[已委售] - [已完成],同时更新订单项中的已成数量
                if (orderInfo.isEnturst() && tradeEntrust.isEntrustAmountAllMatch()) {
                    // 更新sku的库存,此时只更新已成状态的委售单，对于已撤或者部撤的订单统一委托到发货和退货的动作变更库存
                    OrderItem orderItem = orderInfo.getOrderItems().get(0);
                    int outMount = Math.abs(tradeEntrust.getBusinessAmount().intValue());// 已成数量
                    goodsSkuService.deductGoodsStock(orderItem.getSkuId(), outMount, outMount);

                    orderItem.setShippedQuantity(Long.valueOf(outMount));
                    orderInfo.setStatus(EnumsOrderStatus.COMPELETED.getStatus());
                    orderInfo.setCompleteDate(new Date());
                    orderService.updateOrder(orderInfo);
                    
                    //商品打款
                    //receiptOrder(orderInfo);
                }
            }
        }
    }

    /**
     * 给匹配成功的委托人发送短信提醒
     * @param tradeEntrust
     *
     * */
    protected void sendSmsToReciver(TradeEntrust tradeEntrust,TradeMatchDetail detail,String smsCode){
        //只给卖方发送成功短信
        if (detail != null){
            tradeEntrust = detail.getEntrust();
        }
        if (tradeEntrust.isSell()){
            Map<String, String> params = new HashMap<>();
            UserAccountDTO userAccountDTO = remoteUserService.getUserDetailByUserId(tradeEntrust.getUserId());
            if (userAccountDTO == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1001.getErrorNo(),EnumBusinessCode.BUSINESS_1001.getErrorInfo());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(new Date());
            params.put("entrustNo",tradeEntrust.getEntrustNo().toString());
            Long amount = 0L;
            Long incomeAmount=0L;
            if (detail != null){
                //部分成交短信
                //计算本次成交数量
                amount = detail.getMatchAmount();
                //计算剩余商品数量
                Long remainAmount = detail.getSurplusEntrustAmount();
                params.put("remainAmount",remainAmount.toString());
                //计算本次收入金额
                incomeAmount = detail.getMatchFundAmount() - detail.getMatchCommission() - detail.getMatchManagement();
                //计算本次盈利金额=本次收入金额减去成本价
                Long gainBusinessFund = incomeAmount - amount*tradeEntrust.getEntrustPrice();
                params.put("gainBusinessFund",MoneyUtils.getMoneyFormatFen(gainBusinessFund));//金额转换

            }else{
                //全部成交短信
                //计算已成商品数量
                amount = Math.abs(tradeEntrust.getBusinessAmount());
                //计算累计收入
                incomeAmount = tradeEntrust.getGainBusinessFund() + amount*tradeEntrust.getEntrustPrice();
                //计算累计赚得金额
                params.put("gainBusinessFund",MoneyUtils.getMoneyFormatFen(tradeEntrust.getGainBusinessFund()));//金额转换
            }
            params.put("amount",amount.toString());
            params.put("incomeAmount",MoneyUtils.getMoneyFormatFen(incomeAmount));
            remoteSmsService.toUserSendSms(userAccountDTO.getPhone(), smsCode, params, tradeEntrust.getUserId(), date);
        }
    }

    /**
     * 判断要分佣的是否是金莱花号段的会员，该号段的会员不在本平台返佣
     * 金莱花号段的会员不返佣，只打印日志
     * */
    protected Boolean validateIsGoldenFlower(TradeEntrust entrust){
        String account = entrust.getFundAccount().substring(1);
        if (StringUtil.isNotEmpty(goldenFlowerNumberSegment) &&
                account.startsWith(goldenFlowerNumberSegment)){
            logger.info("会员为金莱花号段，本次成交不返佣，委买单编号为："+entrust.getEntrustNo()+",会员交易账号为："+entrust.getFundAccount());
            return true;
        }else {
            return false;
        }
    }
}
